# import urllib.request
# import random
import os
import sys
import re
import requests


def save_image_from_url(image_url, filename):
    """
    Downloads an image from a URL and saves it to a local file.

    Args:
        image_url (str): The URL of the image to download.
        filename (str): The local path and filename to save the image as.
    """

    proxies = {
        "http": '127.0.0.1:10808',
        "https": '127.0.0.1:10808'
    }

    try:
        response = requests.get(image_url, stream=True, proxies=proxies)
        response.raise_for_status()  # Raise an exception for bad status codes

        with open(filename, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)
        print(f"Image downloaded successfully to: {filename}")
    except requests.exceptions.RequestException as e:
        print(f"Error downloading image: {e}")

def save_img_without_appendix(comic_name, chapter_name, pic_name, pic_url):
    if pic_url[-1] == '/':
        appendix = pic_url[:-1].split('.')[-1]
    else:
        appendix = pic_url.split('.')[-1]
    save_img(comic_name, chapter_name, pic_name, pic_url, appendix)
def save_img(comic_name, chapter_name, pic_name, pic_url, appendix):
    comic_name = check_file_name(comic_name)
    chapter_name = check_file_name(chapter_name)
    folder = sys.path[0] + '\\' + comic_name + '\\' + chapter_name
    file_name = folder + '\\' + pic_name + '.' + appendix
    if os.path.exists(file_name):
        return
    if not os.path.exists(folder):
        os.makedirs(folder)
    # opener = urllib.request.build_opener()
    # ua_list = ['Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0',
    #            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
    #            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62',
    #            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0',
    #            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36 SE 2.X MetaSr 1.0'
    #            ]
    # opener.addheaders = [('User-Agent', random.choice(ua_list))]
    # urllib.request.install_opener(opener)
    # req = urllib.request.Request(pic_url)
    # req.set_proxy('127.0.0.1:10808', 'https')
    # req.set_proxy('127.0.0.1:10808', 'http')
    # response = urllib.request.urlopen(req)
    # if not os.path.exists(folder):
    #     os.makedirs(folder)
    # f = open(file_name, 'wb')
    # f.write(response.read())
    # f.close()
    save_image_from_url(pic_url, file_name)
    # print(file_name + ' saved')

def check_file_name(name):
    return re.sub(r'"\\|/|:|\*|\?|\"|<|>|\|"', '', name)

def check_file_exists(file_name):
    return os.path.exists(file_name)